package de.tum.in.eist.poll.client.views.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.in.eist.poll.client.controllers.Controller;
import de.tum.in.eist.poll.shared.beans.Student;

public class StudentListWidget extends Composite {
	private VerticalPanel panel = new VerticalPanel();
	private FlexTable table = new FlexTable();

	public StudentListWidget(Student[] students) {

		Label studentIDLabel = new Label("Student ID");
		Label passwordLabel  = new Label("Password");
		Label deleteLabel    = new Label("Delete");
		
		studentIDLabel.addStyleName("question");
		passwordLabel.addStyleName("question");
		deleteLabel.addStyleName("question");
		
		table.setWidget(0, 0, studentIDLabel);
		table.setWidget(0, 1, passwordLabel);
		table.setWidget(0, 2, deleteLabel);
		
		addStudents(students);

		panel.add(table);
		
		table.addStyleName("table");

		initWidget(panel);
	}

	/**
	 * add a User to the table
	 */
	public void addStudents(Student[] students) {
		// show table only if there are users existing
		if (students != null && students.length > 0) {
			for (int i = 0; i < students.length; i++) {
				final int row = table.getRowCount();
				final Student student = students[i];

				Button deleteButton = new Button("X");
				deleteButton.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						//removes the user from the servers
						Controller.userManagmentController.removeUsers(new String[] {student.getUserID()}, new AsyncCallback<String>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO LONG: show dialog
							}

							@Override
							public void onSuccess(String result) {
								removeStudent(student);
							}
							
						});
					}
				});

				table.setText(row, 0, student.getUserID());
				table.setText(row, 1, student.getPassword());
				table.setWidget(row, 2, deleteButton);
			}
		}
	}

	/**
	 * removes the student from the table
	 * @param student
	 */
	private void removeStudent(Student student) {
		// index starts at 1 (head row)
		for (int i = 1; i < table.getRowCount(); i++) {
			if (table.getText(i, 0).equals(student.getUserID())) {
				table.removeRow(i);
				return;
			}
		}
	}
}
